package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 *  JDK动态代理
 *
 */
public class DynamicProxy implements AopProxy  {
    @Override
    public Object createProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), (proxy, method, args) -> {
            Object invoke = method.invoke(o, args);
            return invoke;
        });
    }

    @Override
    public Object createProxyWithTransaction(Object o, List<Method> methods) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                boolean anyMatch = methods.stream().anyMatch(w -> w.getName().equals(method.getName())
                );
                if (anyMatch) {
                    TransactionManager.getInstance().beginTransaction();
                    try {
                        result = method.invoke(o, args);
                        System.out.println("执行到事务了...");
                    } catch (Exception e) {
                        TransactionManager.getInstance().rollback();
                        throw e;
                    }
                        TransactionManager.getInstance().commit();
                }
//                System.out.println("执行到jdk非事务这了...");
//                result = method.invoke(o, args);
//                System.out.println("执行到jdk非事务完成了...");
                return result;
            }
        });
    }
}
